<template>
    <div class="xing-tree">
      <el-card>
        <p>业务场景</p>
        <p>设置的适合要求把子节点和父节点的id要一起传递过去，即把全选和半选状态的值都传过去</p>
        <p>但回显的需要剔除父节点，只要子节点，父节点的选中状态会根据子节点的变化而变化</p>
      </el-card>
      <div class="tree">
        <el-tree
          ref="tree"
          :data="data"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :props="defaultProps">
        </el-tree>
        <el-button type="primary" size="small" @click="handleGet">获取</el-button>
        <el-button type="primary" size="small" @click="handleResetChecked">清空</el-button>
        <el-button type="primary" size="small" @click="handleEcho">回显</el-button>
      </div>
    </div>
</template>

<script>
export default {
  name: 'Tree',
  data () {
    return {
      data: [{
        id: 1,
        label: '山东省',
        children: [{
          id: 4,
          label: '济南市',
          children: [{
            id: 9,
            label: '历程区'
          }, {
            id: 10,
            label: '章丘区'
          }]
        }]
      }, {
        id: 2,
        label: '北京市',
        children: [{
          id: 5,
          label: '东城区'
        }, {
          id: 6,
          label: '西城区'
        }]
      }, {
        id: 3,
        label: '天津市',
        children: [{
          id: 7,
          label: '塘沽区'
        }, {
          id: 8,
          label: '华尔区'
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      SelectedIdList: []
    }
  },
  methods: {
    handleGet () {
      this.SelectedIdList = Array.from(new Set([...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]))
      console.log(this.SelectedIdList)
    },
    handleResetChecked () {
      this.$refs.tree.setCheckedKeys([])
    },
    handleEcho () {
      let selectedNode = this.SelectedIdList // 返回的所有id
      selectedNode.forEach((item, index, arr) => {
        let node = this.$refs.tree.getNode(arr[index]) // 根据id 拿到 Tree 组件中的node的所有信息
        if (node.isLeaf) { // 判断当前节点是否为子节点
          this.$refs.tree.setChecked(node, true) // 如果是子节点，就把状态设置成选中
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
